package com.hjj.interceptor;

import com.hjj.beans.User;
import com.hjj.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("userServicesFilter")
    UserServices userServices;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        // 获取session中的用户数据
        User user = (User) session.getAttribute("user");

        if (user == null) {

            // 获取所有的cookie
            Cookie[] cookies = request.getCookies();

            // 对cookies进行判空处理,防止后面出现空指针异常
            if (cookies == null){
                // 返回登录页面
                response.sendRedirect("/static/login.html");
                return false;
            }

            String loginAct = "";
            String loginPwd = "";

            // 获取cookies中存储的用户数据
            for (Cookie cookie : cookies) {
                if ("loginAct".equals(cookie.getName())) {
                    loginAct = cookie.getValue();
                } else if ("loginPwd".equals(cookie.getName())) {
                    loginPwd = cookie.getValue();
                }
            }

            // 将获取的用户数据与数据库中的用户数据匹配看是否有
            User temp = userServices.getByUser(loginAct, loginPwd);

            if (temp == null){
                // 返回登录页面
                response.sendRedirect("/static/login.html");
                return false;
            }
            //将登录用户数据出入session对象中
            session.setAttribute("user", temp);
        }

        return true;
    }

    // 响应之后，但是没有到界面【或浏览器】
    // 响应之后【视图解析器之前】
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 响应结束
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
